<script>
export default {
  name: "SelectWarehouse",
}
</script>

<script setup>
import { getWarehouseOptions } from "@/api/public"

const props = defineProps({
  modelValue: {
    type: [Array, String, Number],
    default: () => [],
  },
  valueKey: {
    type: String,
    default: "value",
  },
  labelKey: {
    type: String,
    default: "label",
  },
  isHandle: {
    type: Boolean,
    default: false,
  },
})

const optionsList = ref([])

const initOptionsList = async () => {
  const res = await getWarehouseOptions({ status: 1 })
  optionsList.value = res.data
}

const emit = defineEmits(["update:modelValue"])
const handleChange = (val) => {
  emit("update:modelValue", val)
}

onMounted(() => {
  initOptionsList()
})
const handleCheckAll = (item, type = "") => {
  // let valueList = optionsList.value.map((v) => v[props.valueKey])
  // let attrValue = []
  // // 全选
  // if (type == "all") {
  //   attrValue = valueList
  // }
  // // 反选
  // if (type == "reversion") {
  //   attrValue = valueList.filter((v) => !props.modelValue.includes(v))
  // }
  // emit("update:modelValue", attrValue)

  let valueList = getOpt(optionsList.value, filterValue.value)?.map((v) => v[props.valueKey])
  let attrValue = []
  // 全选
  if (type == "all") {
    attrValue = valueList
  }
  // 反选
  if (type == "reversion") {
    if (filterValue.value) {
      attrValue = optionsList.value.filter((v) => !valueList.includes(v[props.valueKey]))?.map((v) => v[props.valueKey])
    } else {
      attrValue = optionsList.value.filter((v) => !props.modelValue.includes(v[props.valueKey]))?.map((v) => v[props.valueKey])
    }
  }
  emit("update:modelValue", attrValue)
}
const filterValue = ref("")
const filterMethodPlatform = (v) => {
  filterValue.value = v
}
const getOpt = (opt = [], val) => {
  return opt?.filter((v) => v[props.labelKey].toLowerCase().includes(val.toLowerCase())) || []
}
defineExpose({
  optionsList,
})
</script>

<template>
  <el-select :modelValue="modelValue" v-bind="$attrs" filterable @change="handleChange" clearable collapse-tags class="select-wrap" :filter-method="filterMethodPlatform">
    <div v-if="isHandle" class="select-handle">
      <el-button type="primary" link @click="handleCheckAll(item, 'reversion')">反选</el-button>
      <el-button type="primary" link @click="handleCheckAll(item, 'all')">全选</el-button>
    </div>

    <el-option v-for="item in getOpt(optionsList || [], filterValue)" :key="item[valueKey]" :label="item[labelKey]" :value="item[valueKey]" />
  </el-select>
</template>

<style lang="scss" scoped>
.select-handle {
  text-align: right;
  padding: 4px 12px;
}
</style>
